package com.aiti.lulian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.lulian.bo.LoginUserInfo;
import com.aiti.lulian.dto.industry.EnterpriseInfoDto;
import com.aiti.lulian.dto.industry.StarEnterpriseParamDto;
import com.aiti.lulian.dto.industry.StarEnterpriseQueryDto;
import com.aiti.lulian.dto.industry.SysUserInfoDto;
import com.aiti.lulian.entity.industry.CardGovIndustryStarEnterprise;
import com.aiti.lulian.mapper.card.industry.CardGovIndustryStarEnterpriseMapper;
import com.aiti.lulian.service.CardGovIndustryStarEnterpriseService;
import com.aiti.lulian.utils.BusinessUtil;
import com.aiti.lulian.vo.industry.StarEnterpriseInfoVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description: CardGovIndustryStarEnterpriseServiceImpl
 * @auth fcb
 * @date 2025-03-06 14:13
 **/
@Service
@Slf4j
public class CardGovIndustryStarEnterpriseServiceImpl extends BaseSerivceImpl<CardGovIndustryStarEnterpriseMapper, CardGovIndustryStarEnterprise> implements CardGovIndustryStarEnterpriseService {

    private static final String AREA= "诸城市";
    private static final String PROVINCE = "山东省";
    private static final String CITY = "潍坊市";
    private static final String ENTERPRISE_MANAGER_ROLE_ID = "043ea2e3e02c4aa591df1f83e65069bc";

    /**
     * 新增明星企业
     * @param paramDto
     * @param loginUserInfo
     */
    @Transactional(rollbackFor = Throwable.class)
    public void addStartEnterprise(StarEnterpriseParamDto paramDto, LoginUserInfo loginUserInfo) {
        SysUserInfoDto enterpriseManagerUserInfo = this.checkParamAndGetSysUserInfoDto(paramDto, false);

        // 2. 保存数据
        CardGovIndustryStarEnterprise po = new CardGovIndustryStarEnterprise();
        po.setBaseId(UUID.randomUUID().toString());
        po.setIndustryId(paramDto.getIndustryId());
        po.setEnterpriseId(paramDto.getEnterpriseId());
        // 便于后续查询存储一份用户名。如果用户修改了用户名，这里保存的数据会与实际用户名不一致。
        po.setEnterpriseUsername(enterpriseManagerUserInfo.getUsername());
        // 企业管理员账号baseId
        po.setEnterpriseUserBaseId(enterpriseManagerUserInfo.getUserId());
        po.setBaseCreateBy(loginUserInfo.getUserId());

        this.save(po);
    }

    private SysUserInfoDto checkParamAndGetSysUserInfoDto(StarEnterpriseParamDto paramDto, boolean updateFlag) {
        // 1.1.在企业表中查询要添加的企业， 判断该企业是否已经开通企业名片、是否是诸城市的
        EnterpriseInfoDto enterpriseInfo = this.baseMapper.queryEnterpriseInfo(paramDto.getEnterpriseId());
        if(enterpriseInfo == null) {
            throw new BusinessException("企业不存在");
        }
        // 1.2. 判断该企业是否属于诸城市
        this.checkArea(enterpriseInfo);
        // 1.3. 判断该企业是否已经开通企业名片。
        // 用企业id 在card_enterprise_user_data 表里可以查到数据，并且查到的用户id 在cloud_show_system.sys_user 表中未被删除
        String cardUserId = this.baseMapper.queryCardUserId(paramDto.getEnterpriseId());
        if(StrUtil.isEmpty(cardUserId)) {
            throw new BusinessException("该企业未开通企业名片");
        }
        // 判断该用户是否有效
        SysUserInfoDto cardUserInfo = this.baseMapper.queryUserInfo(cardUserId);
        if(cardUserInfo == null) {
            throw new BusinessException("该企业未开通企业名片");
        }
        // 1.4. 查询该企业关联用户，判断该用户是否是企业关联的管理员
        if(StrUtil.isEmpty(enterpriseInfo.getUserId())) {
            throw new BusinessException("该企业没有企业管理员");
        }
        // 这个用户是否还有效
        SysUserInfoDto enterpriseManagerUserInfo = this.baseMapper.queryUserInfo(enterpriseInfo.getUserId());
        if(enterpriseManagerUserInfo == null) {
            throw new BusinessException("该企业没有企业管理员");
        }
        // 这个用户是不是企业管理员
        Integer count = this.baseMapper.getCountUserEnterpriseManagerRole(enterpriseInfo.getUserId(), ENTERPRISE_MANAGER_ROLE_ID);
        if(count == 0) {
            throw new BusinessException("该企业没有企业管理员");
        }
        // 1.5 该企业是否已经被添加
        if(!updateFlag) {
            Integer starEnterpriseCount = this.baseMapper.getStarEnterpriseCount(paramDto.getEnterpriseId(), paramDto.getIndustryId());
            if(starEnterpriseCount > 0) {
                throw new BusinessException("企业已存在");
            }
        }
        return enterpriseManagerUserInfo;
    }

    /**
     * 修改明星企业
     * @param paramDto
     * @param loginUserInfo
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void updateStartEnterprise(StarEnterpriseParamDto paramDto, LoginUserInfo loginUserInfo) {
        if(StrUtil.isEmpty(paramDto.getBaseId()) || StrUtil.isEmpty(paramDto.getEnterpriseId())) {
            throw new BusinessException("参数错误");
        }
        SysUserInfoDto enterpriseManagerUserInfo = this.checkParamAndGetSysUserInfoDto(paramDto, true);
        CardGovIndustryStarEnterprise po = new CardGovIndustryStarEnterprise();
        if(StrUtil.isNotEmpty(paramDto.getIndustryId())) {
            po.setIndustryId(paramDto.getIndustryId());
        }
        po.setEnterpriseId(paramDto.getEnterpriseId());
        po.setEnterpriseUsername(enterpriseManagerUserInfo.getUsername());
        // 企业管理员账号baseId
        po.setEnterpriseUserBaseId(enterpriseManagerUserInfo.getUserId());
        po.setBaseUpdateBy(loginUserInfo.getUserId());
        po.setBaseId(paramDto.getBaseId());

        this.baseMapper.updateStarEnterprise(po);
    }

    /**
     * 删除明星企业
     * @param baseIds
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void deleteStartEnterprise(List<String> baseIds) {
        if(CollectionUtil.isEmpty(baseIds)) {
            return;
        }
        this.baseMapper.deleteStartEnterprise(baseIds);
    }

    /**
     * 查询明星企业列表
     * @param queryDto
     * @return
     */
    @Override
    public PageResult<StarEnterpriseInfoVo> queryIndustryStarEnterpriseList(StarEnterpriseQueryDto queryDto) {
        BusinessUtil.checkPageParam(queryDto);
        IPage<StarEnterpriseInfoVo> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        List<StarEnterpriseInfoVo> list = this.baseMapper.queryIndustryStarEnterpriseList(page, queryDto);
        PageResult<StarEnterpriseInfoVo> pageResult = new PageResult<>(list, new PageInfo(queryDto.getPageNum(), queryDto.getPageSize()), page.getTotal());
        return pageResult;
    }

    /**
     * 明星企业详情
     * @param baseId
     * @return
     */
    @Override
    public StarEnterpriseInfoVo getStarEnterpriseDetail(String baseId) {
        StarEnterpriseInfoVo starEnterpriseInfoVo = this.baseMapper.queryStarEnterpriseDetail(baseId);
        if(starEnterpriseInfoVo == null) {
            throw new BusinessException("数据不存在");
        }
        return starEnterpriseInfoVo;
    }

    /**
     * 判断该企业是否属于诸城市
     * @param enterpriseInfo
     */
    private void checkArea(EnterpriseInfoDto enterpriseInfo) {
        String provinceId = this.baseMapper.queryAreaIdByName(PROVINCE);
        String cityId = this.baseMapper.queryAreaIdByName(CITY);
        String areaId = this.baseMapper.queryAreaIdByName(AREA);
        if(!provinceId.equals(enterpriseInfo.getProvince()) || !cityId.equals(enterpriseInfo.getCity()) || !areaId.equals(enterpriseInfo.getCounty())) {
            throw new RuntimeException("该企业不属于诸城市");
        }
    }
}
